package com.young.nyd.web;

import com.young.cms.model.AdministrativeRegion;
import com.young.cms.service.IAdministrativeRegionService;
import com.young.common.client.ums.UmsClientHelper;
import com.young.common.core.excel.ExcelExport;
import com.young.common.core.excel.ExcelImport;
import com.young.common.core.excel.IExcelExport;
import com.young.common.core.excel.IExcelImport;
import com.young.common.util.CommonUtil;
import com.young.common.util.Result;
import com.young.common.util.StringUtils;
import com.young.common.util.Page;
import com.young.interfaces.log.annotation.Log;
import com.young.nyd.model.UviSuperviseenterprises;
import com.young.nyd.service.IUviSuperviseenterprisesService;
import com.young.nyd.util.XzquUserController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import static com.young.common.util.Result.buildFail;

/**
* 重点监管企业服务
* Created by  on 2018-10-13.
*/
@Controller
@RequestMapping("/nyd/uviSuperviseenterprises")
public class UviSuperviseenterprisesController {

    @Resource(name="uviSuperviseenterprisesService")
    IUviSuperviseenterprisesService service;

    @Resource(name = "administrativeRegionService")//行政区划
    IAdministrativeRegionService administrativeRegionService;

    XzquUserController xzquUserController = new XzquUserController();

    private UviSuperviseenterprises selectListByUserxzqu(UviSuperviseenterprises obj){
        com.young.interfaces.ums.model.User loginUser = UmsClientHelper.getLoginUser();//已登陆用户
        if(loginUser == null){
            return  null;
        }else {
            String companyId = loginUser.getCompanyId();
            Pattern pattern = Pattern.compile("[0-9]*");
            boolean isNumber = pattern.matcher(companyId).matches();
            if (companyId.equals("ROOT")) {

            } else if (companyId.length() == 6 && isNumber) {
                if (companyId.substring(2).equals("0000")) {//省
                    obj.setRegioncode(companyId.substring(0, 3));
                } else if (companyId.substring(4).equals("00")) {//市
                    obj.setRegioncode(companyId.substring(0, 4));
                } else {//县
                    obj.setRegioncode(companyId);
                }
            }else {
                obj.setRegioncode("NON");//未知行政区划
            }
            return  obj;
        }
    }

    /**
    * 获取数据列表
    * @param obj
    * @param request
    * @return
    * @throws Exception
    */
    @Log("查询重点监管企业列表")
    @RequestMapping("/getList")
    @ResponseBody
    public Object getList(UviSuperviseenterprises obj, HttpServletRequest request) throws Exception{
        UviSuperviseenterprises obj1 = selectListByUserxzqu(obj);
        if(obj1==null){
            return Result.build(Result.CodeEnum.SESSION_TIMEOUT);
        }else{
            List<UviSuperviseenterprises> list = service.getList(obj1);
            for(UviSuperviseenterprises u : list){
                AdministrativeRegion a = administrativeRegionService.get(u.getRegioncode());
                u.setRegions(a.getName());
            }
            return new Result(list);
        }



    }

    /**
     * 获取数据列表
     * @param county
     * @param request
     * @return
     * @throws Exception
     */
    @Log("根据行政区划查询重点监管企业列表")
    @RequestMapping("/getListBycounty")
    @ResponseBody
    public Object getList(String county, HttpServletRequest request) throws Exception{

        List<UviSuperviseenterprises> list = service.getListBycounty(county);
        for(UviSuperviseenterprises u : list){
            AdministrativeRegion a = administrativeRegionService.get(u.getRegioncode());
            u.setRegions(a.getName());
        }

        return new Result(list);
    }

    /**
    * 获取分页数据
    * @param obj
    * @param request
    * @return
    * @throws Exception
    */
    @Log("分页查询重点监管企业列表")
    @RequestMapping("/getPage")
    @ResponseBody
    public Object getPage(UviSuperviseenterprises obj, HttpServletRequest request) throws Exception{
        Page page = CommonUtil.getPageFromRequest(request);
        String countyCode = request.getParameter("countyCode");
        String cityCode = request.getParameter("cityCode");
        String provinceCode = request.getParameter("provinceCode");
        UviSuperviseenterprises obj1 = selectListByUserxzqu(obj);
        if(obj1==null){
            return Result.build(Result.CodeEnum.SESSION_TIMEOUT);
        }else {
            if (countyCode != null && !countyCode .equals("")){
                obj1.setRegioncode(countyCode);
            }else if(cityCode != null && !cityCode .equals("")){
                obj1.setRegioncode(cityCode.substring(0,4));
            }else if(provinceCode != null && !provinceCode .equals("")){
                obj1.setRegioncode(provinceCode.substring(0,3));
            }
            List<UviSuperviseenterprises> list = service.getPage(obj1, page);
            for (UviSuperviseenterprises u : list) {
                AdministrativeRegion a = administrativeRegionService.get(u.getRegioncode());
                u.setRegions(a.getName());
            }
            page.setData(list);
            return page;
        }
    }

    /**
    * 获取单条数据
    * @param id
    * @param request
    * @return
    * @throws Exception
    */
    @Log("查询重点监管企业")
    @RequestMapping("/get")
    @ResponseBody
    public Object get(String id, HttpServletRequest request) throws Exception{
        UviSuperviseenterprises obj = service.get(id);

            AdministrativeRegion a = administrativeRegionService.get(obj.getRegioncode());
            obj.setRegions(a.getName());

        return new Result(obj);
    }

    /**
    * 统计数量
    * @param obj
    * @param request
    * @return
    * @throws Exception
    */
    @Log("统计重点监管企业数量")
    @RequestMapping("/count")
    @ResponseBody
    public Object count(UviSuperviseenterprises obj, HttpServletRequest request) throws Exception{
        return new Result(service.count(obj));
    }

    /**
    * 新增
    * @param obj
    * @param request
    * @return
    * @throws Exception
    */
    @Log("新增重点监管企业")
    @RequestMapping("/insert")
    @ResponseBody
    public Object insert(UviSuperviseenterprises obj, HttpServletRequest request) throws Exception{
       String countyCode = request.getParameter("countyCode");
       String cityCode = request.getParameter("cityCode");
       String provinceCode = request.getParameter("provinceCode");
       if (countyCode != null && !countyCode .equals("")){
           obj.setRegioncode(countyCode);
       }else if(cityCode != null && !cityCode .equals("")){
           obj.setRegioncode(cityCode);
       }else if(provinceCode != null && !provinceCode .equals("")){
            obj.setRegioncode(provinceCode);
       }else{
           return buildFail("行政区划为空");
       }

        service.insert(obj);
        return new Result();
    }

    /**
    * 修改
    * @param obj
    * @param request
    * @return
    * @throws Exception
    */
    @Log("修改重点监管企业")
    @RequestMapping("/update")
    @ResponseBody
    public Object update(UviSuperviseenterprises obj, HttpServletRequest request) throws Exception{
        if(obj.getUnlack().equals("0")){
            String provinceCode = request.getParameter("provinceCode");
            String cityCode = request.getParameter("cityCode");
            String countyCode = request.getParameter("countyCode");
            String regioncode ;
            if(countyCode.equals("") || null == countyCode){
                if(cityCode.equals("") || null == cityCode){
                    if (provinceCode.equals("") || null == provinceCode){
                        return buildFail();
                    }else{
                        regioncode = provinceCode;
                    }
                }else{
                    regioncode = cityCode;
                }
            }else{
                regioncode = countyCode;
            }

            obj.setRegioncode(regioncode);
            service.update(obj);
            return new Result();
        }else{
            return new Result(-1,"信息已锁定，请联系省级管理员解除锁定！方能修改");
        }
    }


    /**
     * 锁定
     * @param ids
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @Log("锁定重点监管企业")
    @RequestMapping("/lock")
    @ResponseBody
    public Object lock(String ids, String id, HttpServletRequest request) throws Exception{
        Result result = new Result();
        UviSuperviseenterprises s = new UviSuperviseenterprises();
        int i = 0;
        if(StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            for(String id1 : idArr){
                s.setId(id1);
                s.setUnlack("1");
                i += service.update(s);
            }
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("锁定失败:待锁定编号无效!");
            }
        }else if(StringUtils.isNotBlank(id)){
            s.setId(id);
            s.setUnlack("1");
            i = service.update(s);
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("锁定失败:待锁定编号无效!");
            }
        }else{
            result.setCode(-1);
            result.setInfo("锁定失败:待锁定编号无效!");
        }
        return result;
    }

    /**
     * 解锁
     * @param ids
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @Log("解锁重点监管企业")
    @RequestMapping("/unlock")
    @ResponseBody
    public Object unlock(String ids, String id, HttpServletRequest request) throws Exception{
        Result result = new Result();
        UviSuperviseenterprises s = new UviSuperviseenterprises();
        int i = 0;
        if(StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            for(String id1 : idArr){
                s.setId(id1);
                s.setUnlack("0");
                i += service.update(s);
            }
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("解锁失败:待解锁编号无效!");
            }
        }else if(StringUtils.isNotBlank(id)){
            s.setId(id);
            s.setUnlack("0");
            i = service.update(s);
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("解锁失败:待解锁编号无效!");
            }
        }else{
            result.setCode(-1);
            result.setInfo("解锁失败:待解锁编号无效!");
        }
        return result;
    }

    /**
    * 删除
    * @param ids
    * @param id
    * @param request
    * @return
    * @throws Exception
    */
    @Log("删除重点监管企业")
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(String ids, String id, HttpServletRequest request) throws Exception{
        Result result = new Result();
        if(StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            service.delete(idArr);
        }else if(StringUtils.isNotBlank(id)){
            service.delete(id);
        }else{
            result.setCode(-1);
            result.setInfo("删除失败:待删除编号无效!");
        }
        return result;
    }

    /**
    * 导入
    * @param file
    * @param request
    * @return
    * @throws Exception
    */
    @Log("导入重点监管企业")
    @RequestMapping("/import")
    @ResponseBody
    public Object importExcel(MultipartFile file, HttpServletRequest request) throws Exception{
        Result result = new Result();
        try {
            if (file != null && !file.isEmpty()) {
                //excel导入处理,返回excel中的数据集合
                IExcelImport ei = new ExcelImport(file);//将文件转为ExcelImport对象
                //从excel读取数据
                List<UviSuperviseenterprises> list = ei.getImportDataAsBean(UviSuperviseenterprises.class);
                if (list != null && list.size() > 0){
                    int num = service.batchInsert(list);//批量插入
                    result.setInfo("成功导入数据" + num + "条!");
                }else {
                    result.setCode(-1);
                    result.setInfo("导入失败:excel解析后结果为空!");
                }
            } else {
                result.setCode(-1);
                result.setInfo("导入失败:文件为空!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        }
        return result;
    }

    /**
    * 导出
    * @param obj 查询参数
    * @param request
    * @param response
    * @throws Exception
    */
    @Log("导出重点监管企业")
    @RequestMapping("/export")
    public void exportExcel(UviSuperviseenterprises obj, HttpServletRequest request, HttpServletResponse response,String ids) throws Exception {
        List<UviSuperviseenterprises> list = new ArrayList<UviSuperviseenterprises>();
        if(ids != null && !"".equals(ids)){
            String[] ids1 = ids.split(",");
            for (String id : ids1){
                UviSuperviseenterprises u =  service.get(id);
                list.add(u);
            }
        }else{
            list = service.getList(obj);
        }
        if (list != null && list.size() > 0){
            IExcelExport ee = new ExcelExport();

            ee.insertBeanList(list, UviSuperviseenterprises.class);
            ee.write2Response(response, "重点监管企业_" + System.currentTimeMillis() + ".xls");
        }else{
            response.getWriter().write("数据为空!");
        }
    }

}